package com.Config;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;

/**
 *
 * *这里是数据配置
 */
@Configuration
//加载配置文件
//<!--   引入db.properties-->
//<context:property-placeholder location="classpath:db.properties"/>
@PropertySource("classpath:db.properties")  //括号里写 classpath:具体文件名字
public class C3P0Configuration {
    //依赖注入
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.name}")
    private String name;

    @Value("${jdbc.password}")
    private String password;

    @Bean("dateSource")    //Spring 会将当前方法返回值以指定名称存储到Spring容器中   设置id值
    public DataSource getDataSource() throws Exception{
        //导入c3p0
        //建立对象
        ComboPooledDataSource source = new ComboPooledDataSource();
        //配置数据库信息
        source.setDriverClass(driver);
        source.setJdbcUrl(url);
        source.setUser(name);
        source.setPassword(password);
        //连接数据库 后续操作和普通JDBC一样了
        Connection connection = source.getConnection();
        //打印连接信息，说明连接上了
        System.out.println(connection);
        connection.close();
        return source;
    }
    //注入JDBCTemlpate 对象
    @Bean("jdbcTemplate")
    public JdbcTemplate getjdbcTemplate(DataSource dataSource){   //引入其他bean 直接在参数传入就行
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //事务管理器
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }


}
